/*
 * Name: $RCSfile: StringUtility.java,v $
 * Version: $Revision: 1.1 $
 * Date: $Date: Oct 31, 2011 1:54:00 PM $
 *
 * Copyright (C) 2011 COMPANY_NAME, Inc. All rights reserved.
 */

package hoang.hut.app.utility;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;

import android.content.res.Resources;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.format.Time;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.ClickableSpan;
import android.util.Base64;
import android.widget.EditText;
import android.widget.TextView;

/**
 * StringUtility class
 * 
 * @author Nguyen van Hoang
 * 
 */
public final class StringUtility {
	/**
	 * Check Edit Text input string
	 * 
	 * @param editText
	 * @return
	 */
	public static boolean isEmpty(EditText editText) {
		if (editText == null
				|| editText.getEditableText() == null
				|| editText.getEditableText().toString().trim()
						.equalsIgnoreCase("")) {
			return true;
		}
		return false;
	}

	/**
	 * Check input string
	 * 
	 * @param editText
	 * @return
	 */
	public static boolean isEmpty(String editText) {
		if (editText == null || editText.trim().equalsIgnoreCase("")) {
			return true;
		}
		return false;
	}

	/**
	 * Merge all elements of a string array into a string
	 * 
	 * @param strings
	 *            : mang string
	 * @param separator
	 *            : string ngăn cách
	 * @return
	 */
	public static String join(String[] strings, String separator) {
		StringBuffer sb = new StringBuffer();
		int max = strings.length;
		for (int i = 0; i < max; i++) {
			if (i != 0)
				sb.append(separator);
			sb.append(strings[i]);
		}
		return sb.toString();
	}

	/**
	 * Convert current date time to string
	 * 
	 * @param updateTime
	 * @return
	 */
	public static String convertNowToFullDateString() {
		SimpleDateFormat dateformat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		dateformat.setTimeZone(TimeZone.getTimeZone("GMT"));

		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		return dateformat.format(calendar.getTime());
	}

	public static String getStringFromEditText(TextView editText) {
		if (editText == null)
			return "";
		else
			return editText.getText().toString().trim();
	}

	public static String getStringFromEditText(EditText editText) {
		if (editText == null)
			return "";
		else
			return editText.getText().toString().trim();
	}

	public static boolean verifyEmailPassword(String email) {
		boolean isFormatCorrect = false;

		if (email.contains("@") && email.contains(".") && email.length() >= 6)
			isFormatCorrect = true;

		return isFormatCorrect;
	}

	public static String getTimeFromToSchedule(Date date1, Date date2) {
		String timeStart = getStringTime(date1);
		String timeEnd = getStringTime(date2);

		return timeStart + " - " + timeEnd;
	}

	public static String getStringDate(Date date) {
		// SimpleDateFormat formatDate = new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat formatDate = new SimpleDateFormat("MMMM dd, yyyy");

		String strDate = "";
		strDate += formatDate.format(date.getTime());

		return strDate;
	}

	/**
	 * @author shforever
	 * @param date
	 * @return
	 */
	public static String getStringDate2(Date date) {
		SimpleDateFormat formatDate = new SimpleDateFormat("EEE, MMM dd");

		String strDate = "";
		strDate += formatDate.format(date.getTime());

		return strDate;
	}

	public static String getStringTime(Date date) {
		SimpleDateFormat formatTime = new SimpleDateFormat("h:mm aa");

		String strTime = formatTime.format(date.getTime());
		return strTime;
	}

	public static String getStringDateTime(Date date) {
		SimpleDateFormat formatTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm aa");

		String strDateTime = formatTime.format(date.getTime());
		return strDateTime;
	}

	public static String getStringDateTimeStandard(Date date) {
		SimpleDateFormat formatTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm aa");
		// SimpleDateFormat formatTime = new
		// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String strDateTime = formatTime.format(date.getTime());
		// SmartLog.log("TIMELAST", "getStringDateTimeStandard"+ strDateTime+7);
		return strDateTime;
	}

	/**
	 * Convert current date time to default babble name
	 * 
	 * @return
	 */
	public static String convertNowToTimeStampString() {
		SimpleDateFormat dateformat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm aa");
		return dateformat.format(Calendar.getInstance().getTime());
	}

	/**
	 * Convert to long and then set to reminder
	 * 
	 * @author Camper
	 * @param timeString
	 *            from "2012-09-11 09:51:00" format
	 */
	public static long getMillisecodFromString(String timeString) {
		long millisecond = 0;
		int year, month, day, hour, minute, second;
		year = Integer.parseInt(timeString.substring(0, 4));
		month = Integer.parseInt(timeString.substring(5, 7));
		day = Integer.parseInt(timeString.substring(8, 10));
		hour = Integer.parseInt(timeString.substring(11, 13));
		minute = Integer.parseInt(timeString.substring(14, 16));
		second = Integer.parseInt(timeString.substring(17, 19));

		Time now = new Time();
		now.setToNow();
		Date date = new Date(year - 1900, month - 1, day);
		millisecond = date.getTime() + ((hour * 60 + minute) * 60 + second)
				* 1000 + now.gmtoff * 1000;
		return millisecond;
	}

	public static String getDate(long milliSeconds, String dateFormat) {
		DateFormat formatter = new SimpleDateFormat(dateFormat);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliSeconds);
		return formatter.format(calendar.getTime());
	}

	/**
	 * Decode url
	 * 
	 * @param str
	 * @return
	 */
	public static String decodeString(String str) {
		String decodedString = "";
		try {
			decodedString = URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// SmartLog.log("StringUtility - decodeString", e.getMessage());
		}
		return decodedString;
	}

	/**
	 * Encode url
	 * 
	 * @param str
	 * @return
	 */
	public static String encodeString(String str) {
		String encodedString = "";
		try {
			encodedString = URLEncoder.encode(str, "UTF-8");
			encodedString = encodedString.replace("+", "%20");
		} catch (UnsupportedEncodingException e) {
			encodedString = str;
			// SmartLog.log("StringUtility - encodedString", e.getMessage());
		}
		return encodedString;
	}

	public static String encodeToBase64(byte[] bytes) {
		String base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
		return base64;
	}

	// -----------------------------------------------------------------------
	public static String bytesToHex(byte[] bytes) {
		final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] hexChars = new char[bytes.length * 2];
		int v;
		for (int j = 0; j < bytes.length; j++) {
			v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new String(hexChars);
	}

	public static String sha1hash(String text) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(text.getBytes("UTF-8"), 0, text.length());
			byte[] sha1hash = md.digest();
			return bytesToHex(sha1hash);
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean isEmptyString(String str) {
		return !(str != null && str.trim().length() > 0);
	}

	public static String loadRawResourceString(Resources res, int resourceId)
			throws IOException {
		InputStream is = res.openRawResource(resourceId);
		return loadString(is);
	}

	public static String loadAssetString(Resources res, String filename)
			throws IOException {
		InputStream is = res.getAssets().open(filename);
		return loadString(is);
	}

	public static String loadString(InputStream is) throws IOException {
		StringBuilder builder = new StringBuilder();
		InputStreamReader reader = new InputStreamReader(is);
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			builder.append(buf, 0, numRead);
		}
		return builder.toString();
	}

	public static String[] union(String[] a, String[] b) {
		LinkedList<String> retval = new LinkedList<String>();
		for (int i = 0; i < a.length; i++) {
			retval.add(a[i]);
		}

		for (int i = 0; i < b.length; i++) {
			if (!retval.contains(b[i])) {
				retval.add(b[i]);
			}
		}

		String[] retarray = new String[retval.size()];
		retval.toArray(retarray);
		return retarray;

	}

	public static String[] intersection(String[] a, String[] b) {
		List<String> blist = Arrays.asList(b);
		LinkedList<String> retval = new LinkedList<String>();

		for (int i = 0; i < a.length; i++) {
			if (blist.contains(a[i])) {
				retval.add(a[i]);
			}
		}

		String[] retarray = new String[retval.size()];
		retval.toArray(retarray);
		return retarray;
	}

	public abstract static class ClickSpan extends ClickableSpan {

	}

	public static void clickify(TextView view, final String clickableText,
			final ClickSpan span) {

		CharSequence text = view.getText();
		String string = text.toString();

		int start = string.indexOf(clickableText);
		int end = start + clickableText.length();
		if (start == -1)
			return;

		if (text instanceof Spannable) {
			((Spannable) text).setSpan(span, start, end,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else {
			SpannableString s = SpannableString.valueOf(text);
			s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			view.setText(s);
		}

		MovementMethod m = view.getMovementMethod();
		if ((m == null) || !(m instanceof LinkMovementMethod)) {
			view.setMovementMethod(LinkMovementMethod.getInstance());
		}
	}
}
